package com.memory.monitor.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.memory.monitor.common.DeleteRequest;
import com.memory.monitor.common.ErrorCode;
import com.memory.monitor.constant.ExcelConstant;
import com.memory.monitor.exception.BusinessException;
import com.memory.monitor.exception.ThrowUtils;
import com.memory.monitor.job.MarketExcelListener;
import com.memory.monitor.job.RoleExcelListener;
import com.memory.monitor.mapper.RoleMapper;
import com.memory.monitor.model.dto.role.RoleAddRequest;
import com.memory.monitor.model.dto.role.RoleQuerryRequest;
import com.memory.monitor.model.dto.role.RoleUpdateRequest;
import com.memory.monitor.model.entity.Job;
import com.memory.monitor.model.entity.Market;
import com.memory.monitor.model.entity.Role;
import com.memory.monitor.model.entity.User;
import com.memory.monitor.model.vo.MarketVO;
import com.memory.monitor.model.vo.RoleVO;
import com.memory.monitor.service.RoleService;
import com.memory.monitor.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.annotation.RequestScope;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static com.memory.monitor.constant.ExcelConstant.*;

/**
* @author 21731
* @description 针对表【role(角色管理)】的数据库操作Service实现
* @createDate 2024-09-02 10:00:07
*/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
    implements RoleService {
    @Resource
    private UserService userService;

    @Override
    public RoleVO getRoleVO(Role role) {
        if (role == null) {
            return null;
        }
        RoleVO roleVO = new RoleVO();
        BeanUtils.copyProperties(role, roleVO);
        return roleVO;
    }

    @Override
    public List<RoleVO> getRoleVO(List<Role> roleList) {
        if (CollectionUtils.isEmpty(roleList)) {
            return new ArrayList<>();
        }
        return roleList.stream().map(this::getRoleVO).collect(Collectors.toList());
    }

    /**
     * 查询
     * @param roleQuerryRequest
     * @return
     */
    @Override
    public QueryWrapper<Role> getQueryWrapper(RoleQuerryRequest roleQuerryRequest) {
        if (roleQuerryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = roleQuerryRequest.getId();
        String roleName = roleQuerryRequest.getRoleName();
        String roleEname = roleQuerryRequest.getRoleEname();
        String remark = roleQuerryRequest.getRemark();
        Integer status = roleQuerryRequest.getStatus();

        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.like(StringUtils.isNotBlank(roleName), "role_name", roleName);
        queryWrapper.like(StringUtils.isNotBlank(roleEname), "role_ename", roleEname);
        queryWrapper.like(StringUtils.isNotBlank(remark), "remark", remark);
        queryWrapper.eq(status != null, "status", status);


        return queryWrapper;
    }

    /**
     * 增加
     * @param roleAddRequest
     * @return
     */
    @Override
    public Long addRole(RoleAddRequest roleAddRequest) {
        if (roleAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Role role = new Role();

        BeanUtils.copyProperties(roleAddRequest, role);
        boolean result = this.save(role);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return role.getId();
    }

    /**
     * 修改
     * @param roleUpdateRequest
     * @return
     */
    @Override
    public Boolean updateRole(RoleUpdateRequest roleUpdateRequest) {
        if (roleUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //修改用户表中的角色名信息
        String roleName = roleUpdateRequest.getRoleName();
        Role role = this.getById(roleUpdateRequest.getId());
        // 如果找不到对应的role对象，可以选择抛出异常或返回错误
        ThrowUtils.throwIf(role == null,ErrorCode.PARAMS_ERROR);
        List<User> userlist = userService.lambdaQuery()
                .eq(User::getUserRole, role.getRoleName()).list();
        for (User user : userlist) {
            user.setUserRole(roleName);
        }
        userService.updateBatchById(userlist);


        BeanUtils.copyProperties(roleUpdateRequest,role);
        boolean result = this.updateById(role);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return result;
    }

    /**
     * 删除
     * @param deleteRequest
     * @return
     */
    @Override
    public Boolean deleteRole(DeleteRequest deleteRequest) {
        if (deleteRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 创建查询请求，设置ID
        Role role = this.getById(deleteRequest.getId());
        // 如果找不到对应的role对象，可以选择抛出异常或返回错误
        ThrowUtils.throwIf(role == null,ErrorCode.PARAMS_ERROR);

        //在user表中查询role_title相同的字段 进行同步删除
        List<User> userList = userService.lambdaQuery()
                .eq(User::getJob, role.getRoleName()).list();

        userService.removeBatchByIds(userList);


        boolean result = this.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(result, ErrorCode.OPERATION_ERROR);
        return result;
    }

    @Override
    public List<RoleVO> listRoleByPage() {
        return getRoleVO(this.list());
    }

    @Override
    public Boolean readExcel(MultipartFile multipartFile) {
        // 1.转换文件为字节流
        InputStream inputStream;
        try {
            inputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 2.执行文件处理逻辑
        EasyExcel.read(inputStream, Role.class, new RoleExcelListener()).sheet().doRead();
        // 3.入库
        boolean saveBatch = this.saveBatch(RoleExcelListener.CACHED_DATA_LIST);

        ThrowUtils.throwIf(!saveBatch, ErrorCode.PARAMS_ERROR);
        return true;
    }

    @Override
    public Boolean writeExcel(String path) {
        // 1.定义文件路径
        String fullPath = DOWNLOAD_PATH + AREA_TABLE_NAME;
        // 2.检查文件是否存在
        ExcelConstant.isExist(fullPath);
        // 3.根据路径导出
        List<RoleVO> roleList = this.listRoleByPage();
        EasyExcel.write(fullPath, User.class).sheet(AREA_SHEET_NAME).doWrite(roleList);

        return true;
    }
}




